using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using SanguoXCiv.Logic;

namespace SanguoXCiv
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        MouseState mouseState;
        MouseState prevMouseState;

        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        SpriteFont stateFont;

        Texture2D texture_cursor;
        Texture2D texture_blockhover;
        Texture2D texture_blockhover_thick;
        Texture2D texture1;
        Texture2D texture_troop1;
        Texture2D texture_troop2;
        Texture2D texture_troop_selected;
        Texture2D texture_target;

        Battlefield battlefield1;
        Unit unit1;
        Unit unit2;

        Queue<groundBlock> tempPath;

        public Game1()
        {
            this.IsMouseVisible = true;
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            mouseState = new MouseState();
            prevMouseState = new MouseState();

            battlefield1 = new Battlefield(10, 6);
            unit1 = new Unit();
            unit2 = new Unit(320);

            tempPath = new Queue<groundBlock>();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            texture_cursor = Content.Load<Texture2D>(@"images/cursor");
            texture_blockhover = Content.Load<Texture2D>(@"images/blockhover");
            texture_blockhover_thick = Content.Load<Texture2D>(@"images/blockhover_thick");
            texture1 = Content.Load<Texture2D>(@"images/block_plain");
            texture_troop1 = Content.Load<Texture2D>(@"images/troop1");
            texture_troop2 = Content.Load<Texture2D>(@"images/troop2");
            texture_troop_selected = Content.Load<Texture2D>(@"images/troop_selected");
            texture_target = Content.Load<Texture2D>(@"images/target");

            stateFont = Content.Load<SpriteFont>(@"fonts/State");            
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            prevMouseState = mouseState;
            mouseState = Mouse.GetState();
            ButtonState leftButtonState = mouseState.LeftButton;

            if (mouseState.X >= unit1.x && mouseState.X <= unit1.x + 64 && mouseState.Y >= unit1.y && mouseState.Y <= unit1.y + 64 &&
                mouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Released)
            {
                unit1.RemoveAttackTarget();
                unit1.path.Clear();
                unit1.isSelected = 1;
            }
            if (mouseState.X >= unit2.x && mouseState.X <= unit2.x + 64 && mouseState.Y >= unit2.y && mouseState.Y <= unit2.y + 64 &&
                mouseState.LeftButton == ButtonState.Pressed && prevMouseState.LeftButton == ButtonState.Released)
            {
                unit1.RemoveAttackTarget();
                unit2.path.Clear();
                unit2.isSelected = 1;
            }

            if (prevMouseState.LeftButton == ButtonState.Pressed && mouseState.LeftButton == ButtonState.Released)
            {
                if (unit1.isSelected == 1 && unit2.isMouseOver(mouseState.X, mouseState.Y))
                    unit1.SetAttackTarget(unit2);
                int pathLength = tempPath.Count();
                for (int i = 0; i < pathLength; i++)
                {
                    if (unit1.isSelected == 1)
                        unit1.path.Enqueue(tempPath.Dequeue());
                    else if(unit2.isSelected == 1)
                        unit2.path.Enqueue(tempPath.Dequeue());
                }
                unit1.isSelected = 0;
                unit2.isSelected = 0;
            }

            if (unit1.isSelected == 1 || unit2.isSelected == 1)
            {
                groundBlock targetBlock = new groundBlock( Convert.ToInt16(mouseState.X / battlefield1.GetBlock(0, 0).size),
                    Convert.ToInt16(mouseState.Y / battlefield1.GetBlock(0, 0).size));
                int blockExists = 0;
                foreach (groundBlock pathBlock in tempPath)
                {
                    if (pathBlock.x == targetBlock.x && pathBlock.y == targetBlock.y)
                    {
                        blockExists = 1;
                        break;
                    }
                }
                if(blockExists == 0)
                    tempPath.Enqueue(targetBlock);
            }

            unit1.Move();
            unit2.Move();

            unit1.Attack();
            

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // Start 2D drawing
            spriteBatch.Begin();
            //----Battlefield----
            for (int i = 0; i < battlefield1.width; i++)
                for (int j = 0; j < battlefield1.height; j++)
                {
                    groundBlock selBlock = battlefield1.GetBlock(i, j);
                    Vector2 blockPosition = new Vector2(selBlock.x * selBlock.size, selBlock.y * selBlock.size);
                    spriteBatch.Draw(texture1, blockPosition, Color.White);
                }
            //----Battlefield end----

            //----Troop----
            spriteBatch.Draw(texture_troop1, unit1.GetPos(), Color.White);
            spriteBatch.DrawString(stateFont, "hp:"+ unit1.health, unit1.GetPos(), Color.White);
            spriteBatch.Draw(texture_troop2, unit2.GetPos(), Color.White);
            spriteBatch.DrawString(stateFont, "hp:" + unit2.health, unit2.GetPos(), Color.White);
            //----Troop end----
            spriteBatch.End();


            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);
            //----Block hover----
            Vector2 mousePos = new Vector2(mouseState.X - mouseState.X % battlefield1.GetBlock(0, 0).size,
                                            mouseState.Y - mouseState.Y % battlefield1.GetBlock(0, 0).size);
            if (mouseState.LeftButton == ButtonState.Pressed)
                spriteBatch.Draw(texture_blockhover_thick, mousePos, Color.White);
            else
                spriteBatch.Draw(texture_blockhover, mousePos, Color.DarkGreen);
            //----Block hover end----
            //----Troop selected----
            if(unit1.isSelected == 1)
                spriteBatch.Draw(texture_troop_selected, unit1.GetPos(), Color.White);
            //----Troop selected end----
            foreach (groundBlock pathBlock in tempPath)
            {
                spriteBatch.Draw(texture_blockhover_thick, pathBlock.GetPos(), Color.White);
            }
            foreach (groundBlock pathBlock in unit1.path)
            {
                spriteBatch.Draw(texture_blockhover, pathBlock.GetPos(), Color.White);
            }
            foreach (groundBlock pathBlock in unit2.path)
            {
                spriteBatch.Draw(texture_blockhover, pathBlock.GetPos(), Color.White);
            }
            if (unit1.attackTarget != null && unit1.attackTarget.isMouseOver(mouseState.X, mouseState.Y) && mouseState.LeftButton == ButtonState.Pressed)
                spriteBatch.Draw(texture_target, unit1.attackTarget.GetPos(), Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}
